package gateway;

import lombok.Getter;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;

@UtilityClass
public class ServicesHolder {
    private String registryPath = Constants.ZK_REGISTRY;
    @Getter
    private List<String> serviceNames = new CopyOnWriteArrayList<>();
    {
        addServiceName("order");
        addServiceName("product");
        addServiceName("pay");
    }
    private ConcurrentSkipListMap<String, String> servicePaths = new ConcurrentSkipListMap<>();
    private ConcurrentSkipListMap<String, List<String>> addresses = new ConcurrentSkipListMap<>();

    private void addServiceName(String serviceName){
        serviceNames.add(serviceName);
    }

    public String addServicePath(String serviceName){
        String servicePath = getServicePath(serviceName);
        servicePaths.put(serviceName, servicePath);
        return servicePath;
    }

    public String addAddress(String serviceName, String address){
        String servicePath = getServicePath(serviceName);
        addresses.getOrDefault(servicePath, new CopyOnWriteArrayList<>()).add(address);
        return servicePath;
    }
    private String servicePath(String serviceName){
        return registryPath + "/" + serviceName;
    }
    public void addAddress(String servicePath, List<String> addressList){
        addresses.getOrDefault(servicePath, new CopyOnWriteArrayList<>()).clear();
        addresses.put(servicePath, addressList);
    }
    /*public void addressClear(String servicePath){
        addresses.getOrDefault(servicePath, new CopyOnWriteArrayList<>()).clear();
    }*/
    public String getServicePath(String serviceName){
        return servicePaths.get(serviceName);
    }

    public int addressSize(String serviceName){
        return addresses.getOrDefault(serviceName, new CopyOnWriteArrayList<>()).size();
    }

    public String getAddress(String serviceName, int index){
        return addresses.getOrDefault(serviceName, new CopyOnWriteArrayList<>()).get(index);
    }
}
